package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 设置请求编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        //2. 获取用户名参数
        String username = request.getParameter("username");

        //3. 调用service查询
        UserService service = new UserServiceImpl();
        User u = service.findByName(username);

        //4. 判断User是否存在, 返回不同的提示信息
        PrintWriter writer = response.getWriter();
        if (u == null) {
            // 用户名不存在, 可以是可用
            writer.write("<font color='green'>用户名可用~</font>");
        } else {
            // 用户名存在, 可以是不可用
            writer.write("<font color='red'>用户名不可用~</font>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
